# -*- coding:utf-8 -*-
"""
服务端入口
"""
import MyFunc
import SocketServer
import json
import time

'''
保存连接到该服务的客户端列表
'''
global_Client = {}

'''
由于是局域网应用，所以没有做授权验证
'''


class MyRequestServer(SocketServer.BaseRequestHandler):
    def handle(self):
        conn = self.request
        '''
        1,将127.0.0.1 格式地址修改为局域网内格式
        2,然后加入客户端列表中
        3,发送新的客户端列表给所有客户端
        '''
        address = conn.getpeername()
        print address
        if '192.168.13' in address[0]:
            host = address[0]
        else:
            host = MyFunc.getIp(False)

        global_Client[host] = {
            'obj': conn,
            'control': ''
        }
        send_list()
        try:
            pass
            while True:
                time.sleep(0.001)
                ret_b = conn.recv(9000)
                print ret_b
                if ret_b:
                    for ret_bytes in MyFunc.format_recv(ret_b):
                        ret_bytes = json.loads(ret_bytes)

                        if ret_bytes['action'] == 'keyboard':  # 键盘事件,发送按键id给当前连接所控制的ip
                            if global_Client[host]['control']:
                                send_message = {
                                    'action': 'keyboard',
                                    'data': ret_bytes['data']
                                }
                                send_message = json.dumps(send_message)
                                print send_message
                                global_Client[global_Client[host]['control']]['obj'].send(send_message)

                        if ret_bytes['action'] == 'control':  # 切换控制
                            global_Client[host]['control'] = MyFunc.getIp(ret_bytes['data'])

        except Exception, exc:
            # 断开异常链接，并发送新的列表给每个连接
            print exc
            del global_Client[host]

            send_list()


class MyServer:
    def __init__(self):
        self.server = SocketServer.ThreadingTCPServer(('0.0.0.0', 8080), MyRequestServer)
        self.run()

    def run(self):
        print "写入配置文件...\r\n请将配置文件复制到客户端同级目录下...".decode('utf-8').encode('gbk')
        create_config()
        print "开始监听".decode('utf-8').encode('gbk')
        self.server.serve_forever()


def send_list():
    """
    发送新的连接列表给所有客户端
    :return: void
    """
    send_message = {
        'action': 'list',
        'data': [x for x in global_Client]
    }
    for single_conn in global_Client:
        global_Client[single_conn]['obj'].send(json.dumps(send_message))


def create_config():
    server_ip = MyFunc.getIp(False)
    with open('./server.conf', 'w') as fh:
        print server_ip
        fh.write(server_ip)


if __name__ == "__main__":
    server = MyServer()
